package com.handu.luna.boss.controller;

import com.handu.luna.core.domain.promotion.*;
import com.handu.luna.core.domain.search.BonusPromotionSearch;
import com.handu.luna.core.domain.user.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * Created by wangzailiang on 2014/6/20.
 */
@Controller
@RequestMapping("/promotion/redpacket/*")
public class RedPacketPromotionController extends BaseController {

     @RequestMapping(value = "index",method = RequestMethod.GET)
    public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException {

        BonusPromotionSearch bonusPromotionSearch;
        BossModel bossModel = createModel("promotion/redpacket/index");
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			bonusPromotionSearch = (BonusPromotionSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), BonusPromotionSearch.class);
		}else{
			bonusPromotionSearch = new BonusPromotionSearch();
            viewState = "";
		}
        return bossModel
                .add("redPacketPromotionPage", new RedPacketPromotion().findAll(RedPacketPromotion.selectCondition(bonusPromotionSearch),pageable))
                .add("bonusPromotionSearch", bonusPromotionSearch)
                .add("grantTypeList", BonusPromotion.GrantType.values())
                .add("statusValues", Promotion.PromotionStatus.values())
                .add("viewState", viewState);
    }

    @RequestMapping(value = "index",method = RequestMethod.POST)
    public BossModel index(BonusPromotionSearch bonusPromotionSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException {

        BossModel bossModel = createModel();
        return bossModel
                .add("redPacketPromotionPage", new RedPacketPromotion().findAll(RedPacketPromotion.selectCondition(bonusPromotionSearch),pageable))
                .add("bonusPromotionSearch", bonusPromotionSearch)
                .add("grantTypeList", BonusPromotion.GrantType.values())
                .add("statusValues", Promotion.PromotionStatus.values())
                .add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(bonusPromotionSearch).toString().getBytes("UTF-8")));
    }



    @RequestMapping(value = "grant/{redPacketPromotionId}")
    public BossModel grant(@PathVariable Long redPacketPromotionId) {

        return getGrantModel(redPacketPromotionId);

    }

    @RequestMapping(value = "grant_userRank")
    public BossModel grant_userRank(Long redPacketPromotionId, Long userRankId,RedirectAttributes redirectAttributes) {
        RedPacketPromotion redPacketPromotion = context.getRedPacketPromotionRepository().findOne(redPacketPromotionId);

        long grantNum = new RedPacket().saveByUserRankId(userRankId,redPacketPromotionId);
        if(grantNum > 0) {
            redirectAttributes.addFlashAttribute("message", "成功发放红包\t"+redPacketPromotion.getName() +"\t"+ grantNum +"张");
        }
        return createModel("redirect:index");
    }

    @RequestMapping(value = "userSearch",produces = {"application/json;charset=UTF-8"})
    public  @ResponseBody
    String userSearch(@RequestParam(value = "username", required = false) String username) {

        List<User> userList = context.getUserRepository().findByNameLike("%"+username+"%");
        JSONArray jsonArray = JSONArray.fromObject(userList);
        return jsonArray.toString();
    }


    @RequestMapping(value = "grant_user")
    public BossModel grant_user(Long redPacketPromotionId, Long[] userIdArray,RedirectAttributes redirectAttributes) {
        if(null == userIdArray) {
            return createModel("redirect:index");
        }
        List<Long> userIdList = new ArrayList<>();
        for(Long userid : userIdArray) {
            userIdList.add(userid);
        }
        RedPacketPromotion redPacketPromotion = context.getRedPacketPromotionRepository().findOne(redPacketPromotionId);
        long grantNum = new RedPacket().saveByUsersId(userIdList,redPacketPromotionId);

        redirectAttributes.addFlashAttribute("message", "成功发放红包\t"+redPacketPromotion.getName() +"\t"+ grantNum +"张");
        return createModel("redirect:index");
    }

    @RequestMapping(value = "grant_underline")
    public BossModel grant_underline(Long grantNum,Long redPacketPromotionId,RedirectAttributes redirectAttributes) {

        RedPacketPromotion redPacketPromotion = context.getRedPacketPromotionRepository().findOne(redPacketPromotionId);

        new RedPacket().save(redPacketPromotionId,grantNum);
        redirectAttributes.addFlashAttribute("message", "成功发放红包\t"+ redPacketPromotion.getName()+"\t"+grantNum+"张");
        return createModel("redirect:index");
    }

    @RequestMapping(value = "view/index/{redPacketPromotionId}")
    public BossModel view(@PathVariable Long redPacketPromotionId,String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) {

        String state = "";
        if(viewState != null) {
            state = viewState;
        }
        return createModel("/promotion/redpacket/view/index")
                .add("redPacketPromotionId",redPacketPromotionId)
                .add("redPacketPage", new RedPacket().findAllByRedPacketPromotionId(redPacketPromotionId,pageable))
                .add("viewState",state);
    }

    @RequestMapping(value = "export/{redPacketPromotionId}")
    public BossModel export(@PathVariable Long redPacketPromotionId,HttpServletResponse response) {

        RedPacketPromotion redPacketPromotion = new RedPacketPromotion().findOne(redPacketPromotionId);

        HSSFWorkbook wb = new RedPacket().getExcelModel(redPacketPromotionId);

        //String  mimetype = "application/x-msdownload";
        String fileName = redPacketPromotion.getName();
        //String inlineType = "attachment";
        try {
            response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1" ) + ".xls\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            wb.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value="add",method = RequestMethod.GET)
    public BossModel add() {

        RedPacketPromotion redPacketPromotion = new RedPacketPromotion();
        List<BonusPromotion.UseRange> useRangeList = new ArrayList<>();
        useRangeList.add(BonusPromotion.UseRange.WEBSITE);
        redPacketPromotion.setUseRangeList(useRangeList);
        redPacketPromotion.setGrantType(BonusPromotion.GrantType.USER);

        return getEditModel(redPacketPromotion);
    }

    @RequestMapping(value="edit/{id}",method = RequestMethod.GET)
    public BossModel edit(@PathVariable Long id) {

        RedPacketPromotion redPacketPromotion = new RedPacketPromotion().findOne(id);

        return getEditModel(redPacketPromotion);
    }

    @RequestMapping(value="save",method = RequestMethod.POST)
    //@InitBinder(value = {"name","bonusPrice","limitPrice","grantType","grantStartDate","grantEndDate","useStartDate","useEndDate","remark","grantLimitPrice","goodsIds","useRanges"})
    public BossModel save(@Valid final RedPacketPromotion redPacketPromotion, final BindingResult bindingResult, RedirectAttributes redirectAttributes) {

        if(null == redPacketPromotion.getGrantStartDate()) {
            bindingResult.rejectValue("grantStartDate","","发放开始时间不能为空");
        }
        if(null == redPacketPromotion.getGrantEndDate()) {
            bindingResult.rejectValue("grantEndDate","","发放结束时间不能为空");
        }
        if(null == redPacketPromotion.getUseStartDate()) {
            bindingResult.rejectValue("useStartDate","","使用开始时间不能为空");
        }
        if(null == redPacketPromotion.getUseEndDate()) {
            bindingResult.rejectValue("useEndDate","","使用结束时间不能为空");
        }
        if(null != redPacketPromotion.getGrantStartDate() && null !=redPacketPromotion.getGrantEndDate()) {
            if(redPacketPromotion.getGrantStartDate().compareTo(redPacketPromotion.getGrantEndDate()) != -1) {
                bindingResult.rejectValue("grantStartDate","","发放开始时间必须小于发放结束时间");
            }
        }
        if(null != redPacketPromotion.getUseStartDate() && null !=redPacketPromotion.getUseEndDate()) {
            if(redPacketPromotion.getUseStartDate().compareTo(redPacketPromotion.getUseEndDate()) != -1) {
                bindingResult.rejectValue("useStartDate","","使用开始时间必须小于使用结束时间");
            }
        }
        if(null != redPacketPromotion.getGrantStartDate() && null !=redPacketPromotion.getUseStartDate()) {
            if(redPacketPromotion.getGrantStartDate().compareTo(redPacketPromotion.getUseStartDate()) != -1) {
                bindingResult.rejectValue("grantStartDate","","发放开始时间必须小于使用开始时间");
            }
        }
        if(null == redPacketPromotion.getUseRangeList() || redPacketPromotion.getUseRangeList().size() == 0) {
            bindingResult.rejectValue("useRangeList","","至少选择一项");
        }

        if(null == redPacketPromotion.getBrandIdList() || redPacketPromotion.getBrandIdList().size() == 0) {
            bindingResult.rejectValue("brandIdList","","至少选择一项");
        }

        if(null != redPacketPromotion.getGrantType()) {
            switch (redPacketPromotion.getGrantType()) {
                case GOOD:
                    if(null == redPacketPromotion.getGoodsIds() || "".equals(redPacketPromotion.getGoodsIds())) {
                        bindingResult.rejectValue("goodsIds","","请输入商品ID");
                    }
                    break;
                case ORDER:
                    if(null == redPacketPromotion.getGrantLimitPrice()) {
                        bindingResult.rejectValue("grantLimitPrice","","请输入发放红包的最小订单金额");
                    }
                default:
            }
        }


        if(bindingResult.hasErrors()) {
            return getEditModel(redPacketPromotion);
        }
        redirectAttributes.addFlashAttribute("message", redPacketPromotion.getSucessFlashMessage("红包类型"));
        redPacketPromotion.save(redPacketPromotion);
        return createModel("redirect:index");
    }

    @RequestMapping(value="delete",method= RequestMethod.POST)
    public BossModel delete(String viewState,Long redPacketPromotionId,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
        context.getRedPacketPromotionRepository().delete(redPacketPromotionId);
        context.getRedPacketRepository().deleteByBonusPromotionId(redPacketPromotionId);
        return createModel("/promotion/redpacket/redpacketpromotion_table")
                .add("redPacketPromotionPage",new RedPacketPromotion().findAll(null,pageable))
                .add("viewState",viewState);
    }

    @RequestMapping(value="deleteRedPacket",method= RequestMethod.POST)
    public BossModel deleteRedPacket(String viewState,Long id,Long redPacketPromotionId,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
        new RedPacket().delete(id,redPacketPromotionId);
        return createModel("/promotion/redpacket/view/redpacket_table")
                .add("redPacketPromotionId",redPacketPromotionId)
                .add("redPacketPage", new RedPacket().findAllByRedPacketPromotionId(redPacketPromotionId,pageable))
                .add("viewState",viewState);
    }

    public BossModel getEditModel(RedPacketPromotion redPacketPromotion) {

        return createModel("/promotion/redpacket/info")
                .add("redPacketPromotion", redPacketPromotion)
                .add("brandList", context.getBrandRepository().findAll())
                .add("useRangeValues", RedPacketPromotion.UseRange.values())
                .add("grantTypeList", RedPacketPromotion.GrantType.values());
    }

    /**
     * 根据发放类型选择视图
     * @param redPacketPromotionId
     * @return
     */
    private BossModel getGrantModel(Long redPacketPromotionId) {

        RedPacketPromotion redPacketPromotion = new RedPacketPromotion().findOne(redPacketPromotionId);

        BossModel bossModel = null;
        switch (redPacketPromotion.getGrantType()) {
            case USER :
                bossModel = createModel("/promotion/redpacket/grant/grant_user")
                        .add("userRankList",context.getUserRankRepository().findAllNotSpecial())
                        .add("userList",context.getUserRepository().findAll())
                        .add("redPacketPromotion",redPacketPromotion)
                        .add("userIdList",new ArrayList<Long>());
                break;
            case UNDERLINE:
                bossModel = createModel("/promotion/redpacket/grant/grant_underline")
                        .add("redPacketPromotion",redPacketPromotion);
                break;
            default:
                System.out.println("default");
        }

        return bossModel;

    }

    public BossModel getViewModel() {

        return createModel("/promotion/redpacket/view/index");
    }
}
